package com.songsong.myblog2.controller;

import com.songsong.myblog2.component.StringAndArray;
import com.songsong.myblog2.domain.Article;
import com.songsong.myblog2.domain.User;
import com.songsong.myblog2.service.*;
import com.songsong.myblog2.util.BuildArticleTabloidUtil;
import com.songsong.myblog2.util.TimeUtil;
import io.netty.handler.codec.http.HttpRequest;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 处理文章的controller
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    /*注入articleService*/
    @Resource(name = "articleService")
    private ArticleService articleService;
    /*注入userService*/
    @Autowired
    private UserService userService;
    /*注入tagService*/
    @Resource(name = "tagService")
    private TagService tagService;
    /*注入archivesService*/
    @Resource(name = "archivesService")
    private ArchivesService archivesService;
    /*注入categoriesService*/
    @Resource(name = "categoriesService")
    private CategoriesService categoriesService;

    /**
     * 添加文章
     *
     * @param article
     * @param request
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public JSONObject addArticle(Article article, HttpServletRequest request) {

        String username = (String) SecurityUtils.getSubject().getPrincipal();
        //根据用户手机号查找到该用户
        User user = userService.findUser(username);
        //设置用户id
        article.setUserId(user.getId());
        //设置文章作者
        article.setArticleAuthor(user.getUsername0());
        /**
         * 文章测试代码
         */
        JSONObject returnJson = new JSONObject();
        //获得文章html代码并生成摘要
        BuildArticleTabloidUtil buildArticleTabloidUtil = new BuildArticleTabloidUtil();
        String articleHtmlContent = buildArticleTabloidUtil.buildArticleTabloid(request.getParameter("articleHtmlContent"));
        article.setArticleTabloid(articleHtmlContent + "...");

        String[] articleTags = request.getParameterValues("articleTagsValue");
        String[] tags = new String[articleTags.length + 1];
        for (int i = 0; i < articleTags.length; i++) {
            //去掉可能出现的换行符
            articleTags[i] = articleTags[i].replaceAll("<br>", "");
            tags[i] = articleTags[i];
        }
        tags[articleTags.length] = article.getArticleType();
        //添加标签
        /*调用添加标签的方法添加标签 如果该标签已经存在就将其数量+1  如果不存在就创建该标签*/
        for (int i = 0; i < tags.length; i++) {
            String tag = tags[i];
            /*调用方法先判断该标签是否存在*/
            String s = tagService.selectTag(tag);
            if (s == null) {
                /*不存在就创建*/
                tagService.addTag(tag);
            } else {
                /*存在就将该标签数目+1*/
                tagService.updateTagNum(tag);
            }
        }
        TimeUtil timeUtil = new TimeUtil();
        String nowDate = timeUtil.getFormatDateForThree();
        article.setArticleTags(StringAndArray.arrayToString(tags));
        //获取id  如果id存在就是修改文章
        String id = request.getParameter("articleId");
        //修改文章
        if (!"".equals(id) && id != null) {
            return articleService.updateArticleById(article);
        }
        article.setArticleDate(nowDate);
        //添加归档(如果没有就创建)
        if (archivesService.selectArchive(article.getArticleDate())) {
            /*如果不存在就创建*/
            archivesService.addArchives(article.getArticleDate());
        } else {
            /*如果存在就将该数量+1*/
            archivesService.updateArchiveNum(article.getArticleDate());
        }
        //将该分类数量+1
        categoriesService.updateCategoriesNum(article.getArticleCategories());
        /*获取当前的时间戳 作为文章的唯一标识id*/
        article.setArticleId(timeUtil.getLongTime());
        /*设置url*/
        article.setArticleUrl("/findArticle/" + article.getArticleId());
        returnJson.put("status", 200);//返回状态信息
        returnJson.put("articleTitle", article.getArticleTitle());
        returnJson.put("updateDate", article.getArticleDate());
        returnJson.put("author", article.getArticleAuthor());
        returnJson.put("articleUrl", article.getArticleUrl());
        /*调用service*/
        articleService.addArticle(article);
        return returnJson;
    }

    /**
     * 编辑文章
     *
     * @param articleId
     * @param request
     * @return
     */
    @RequestMapping("/update/{articleId}")
    public String updateArticle(@PathVariable("articleId") String articleId, HttpServletRequest request) {
        System.out.println("接受到文章的id" + articleId);
        //将接受到的id放到session中 方便以后查找
        if (!"".equals(articleId)) {
            request.getSession().setAttribute("id", articleId);
        }
        return "anon/editor";
    }

    /**
     * 获得修改文章
     */
    @GetMapping("/getUpdateArticle")
    @ResponseBody
    public JSONObject getDraftArticle(HttpServletRequest request) {
        JSONObject returnJson = new JSONObject();
        String id = (String) request.getSession().getAttribute("id");
        //判断是否为修改文章
        if (id != null) {
            request.getSession().removeAttribute("id");
            returnJson.put("status", 201);
            Article article = articleService.findArticleById(Integer.parseInt(id));
            int lastItem = article.getArticleTags().lastIndexOf(',');
            String[] articleTags = StringAndArray.stringToArray(article.getArticleTags().substring(0, lastItem));
            returnJson.put("result", articleService.getDraftArticle(article, articleTags));
            return returnJson;
        }
        returnJson.put("status", 200);
        return returnJson;
    }
    //删除文章

    /**
     * 删除文章
     *
     * @param deleteArticleId 文章id
     * @return 1--删除成功   0--删除失败
     */
    @RequestMapping("/deleteArticle/{deleteArticleId}")
    @ResponseBody
    public int deleteArticle(@PathVariable("deleteArticleId") String deleteArticleId) {
        if ("".equals(deleteArticleId) || deleteArticleId == null) {
            return 0;
        }
        return articleService.deleteArticle(Long.parseLong(deleteArticleId));
    }
}
